﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.IO;

namespace TcpTestServer
{
    class TcpTestServer
    {
        static TcpListener listener;
        const int LIMIT = 5; //5 concurrent clients


        public  void StartListeners()
        {
            listener = new TcpListener(222);
            listener.Start();
           

            Console.WriteLine("Server mounted, listening to port 222");

            for (int i = 0; i < LIMIT; i++)
            {
                Thread t = new Thread(new ThreadStart(Service));
                t.Start();
            }
        }
        private void Service()
        {
            while (true)
            {
                Socket soc = listener.AcceptSocket();
                
                //soc.SetSocketOption(SocketOptionLevel.Socket,

                //        SocketOptionName.ReceiveTimeout,10000);


                Console.WriteLine("Connected: {0}", 
                                         soc.RemoteEndPoint);

                try
                {
                    Stream s = new NetworkStream(soc);
                    StreamReader sr = new StreamReader(s);
                    StreamWriter sw = new StreamWriter(s);
                    sw.AutoFlush = true; // enable automatic flushing

         
                    while (true)
                    {
                        string message = sr.ReadLine();
                        if (message == "" || message == null) break;
                        Console.WriteLine("Message received : " + message);
                        sw.WriteLine("Server: " + message);
                    }
                    s.Close();
                }
                catch (Exception e)
                {

                    Console.WriteLine(e.Message);

                }

                Console.WriteLine("Disconnected: {0}", 
                                        soc.RemoteEndPoint);

                soc.Close();
            }
        }

    }
}
